import React from 'react'
import { Modal, message } from 'antd'
import CategoryForm from './categoryForm'
import { add, list, update } from '@/api/category-api.js'
class AddCategory extends React.Component {
  state = {
    visible: false,
    confirmLoading: false,
    parentCategorys: [],
    isUpdate: false,
    form: {},
  }
  showModal = (v) => {
    list(0).then((res) => {
      this.setState({
        visible: true,
        parentCategorys: res.data,
        isUpdate: !!v,
        form: v || {},
      })
    })
  }

  handleOk = () => {
    this.setState({
      confirmLoading: true,
    })
    const categoryForm = this.refs.categoryForm
    categoryForm.validateFields((err, values) => {
      if (!err) {
        values.categoryId = this.state.form._id
        ;(this.state.isUpdate ? update(values) : add(values)).then((res) => {
          if (res.status === 0) {
            this.setState(
              {
                visible: false,
                confirmLoading: false,
              },
              () => {
                this.clearForm()
                this.props.getList()
              }
            )
          } else {
            message.error(res.msg || '保存失败')
            this.setState({
              confirmLoading: false,
            })
          }
        })
      }
    })
  }
  clearForm() {
    this.refs.categoryForm.resetFields()
  }
  handleCancel = () => {
    this.setState(
      {
        visible: false,
      },
      () => {
        this.clearForm()
      }
    )
  }
  render() {
    const { visible, confirmLoading } = this.state
    return (
      <div>
        <Modal
          title={this.state.isUpdate ? '更新' : '新增'}
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
        >
          <CategoryForm
            selectDisabled={this.state.isUpdate}
            setForm={this.state.form}
            parentCategorys={this.state.parentCategorys}
            ref="categoryForm"
          />
        </Modal>
      </div>
    )
  }
}
export default AddCategory
